import { defineStore } from 'pinia';
import { ref } from 'vue';
import * as userApi from '@/api/user';
import * as memberApi from '@/api/member';

export const useUserStore = defineStore('user', () => {
	const user = ref<any>({
		// id: null,
		// nickName: '黄先生',
		// avatarUrl: '',
		// memberNo: null,
		// expirationDate: null,
		// isMember: false
	});

	const isLogin = ref(true);

	async function getUserInfo() {
		const response = await userApi.getUserInfo();
		if (response.code === 20000) {
			const data = response.data.user;
			user.value = {
				id: data.id,
				nickName: data.nickName || data.wechat?.nickName,
				createdAt: data.createdAt,
				avatarUrl: data.avatar?.url || data.wechat.avatarUrl
			};
			// let newUser: any = {};
			// if (response.data.length > 0) {
			// 	newUser.memberNo = '123456';
			// 	newUser.expirationDate = dayjs(response.data[0].endTime * 1000).format('YYYY/MM/DD');
			// 	newUser.isMember = true;
			// } else {
			// 	newUser.memberNo = null;
			// 	newUser.expirationDate = null;
			// 	newUser.isMember = false;
			// }
			// user.value = newUser;
		}
	}

	async function setToken(value: string) {
		uni.setStorageSync('token', value);
	}

	async function doJoinMember() {
		const response = await memberApi.createMemberOrder({
			memberCardId: 1,
			planId: 1,
			payMethod: 'wechat',
			isAutoRenew: false
		});
		if (response.code === 200) {
			return response.data;
		}
		return {};
	}

	return {
		user,
		isLogin,
		getUserInfo,
		doJoinMember,
		setToken
	};
});
